package org.csu.jpetstoreagain.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.csu.jpetstoreagain.domain.*;
import org.csu.jpetstoreagain.service.CartService;
import org.csu.jpetstoreagain.service.CatalogService;
import org.csu.jpetstoreagain.service.ItemService;
import org.csu.jpetstoreagain.service.OrderService;
import org.csu.jpetstoreagain.vo.LineItemVO;
import org.csu.jpetstoreagain.vo.MyOrderVO;
import org.csu.jpetstoreagain.vo.NewOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.sound.midi.InvalidMidiDataException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private CatalogService catalogService;

    @RequestMapping("/myOrder")
    public String myOrder(HttpServletRequest httpServletRequest, Model model){
        //登录验证
        HttpSession session = httpServletRequest.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        if (loginAccount == null) {
            return "/jsp/account/signon";
        }

        //VO对象实例化
        List<Order>orders = orderService.getOrdersByUserid(loginAccount.getUserid());
        List<MyOrderVO>VOList = new ArrayList<>();
        for(Order order:orders){
            List<LineItemVO>lineItemVOList = new ArrayList<>();
            List<LineItem> lineItems = orderService.getLineItemsByOrderId(order.getOrderId());
            for(LineItem lineItem:lineItems){
                LineItemVO lineItemVO = new LineItemVO(lineItem,catalogService.getItem(lineItem.getItemId()),catalogService.getProduct(catalogService.getItem(lineItem.getItemId()).getProductid()).getName());
                lineItemVOList.add(lineItemVO);
            }
            MyOrderVO myOrderVO = new MyOrderVO();
            myOrderVO.setOrder(order);
            myOrderVO.setLineItemVOs(lineItemVOList);
            VOList.add(myOrderVO);
        }
        model.addAttribute("VOList",VOList);
        return "/jsp/order/myOrder";
    }

    @RequestMapping({"/newOrder","jsp/order/newOrder"})
    public String newOrder(HttpServletRequest req, Model model, RedirectAttributes redirectAttributes){
        HttpSession session = req.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        String userid=loginAccount.getUserid();
        if (loginAccount == null) {
            return "/jsp/account/signon";
        }
        List<NewOrderVO>newOrderVOList = new ArrayList<>();
        List<Cart> list = cartService.listByUserId(userid);
        ArrayList<CartItem> cartItems = new ArrayList<>();
        BigDecimal subTotal = BigDecimal.valueOf(0);
        List<Item>items = new ArrayList<>();
        Boolean isLack = false;
        for (Cart cart : list) {
            NewOrderVO newOrderVO = new NewOrderVO();
            CartItem cartItem = new CartItem();
            Item item = itemService.getById(cart.getItemId());
            cartItem.setItem(item);
            int quantity = cart.getQuantity();
            cartItem.setQuantity(quantity);
            cartItem.setItemId(item.getItemid());
            BigDecimal listprice = item.getListprice();
            BigDecimal total =  listprice.multiply(BigDecimal.valueOf(quantity));
            cartItem.setTotal(total);
            cartItems.add(cartItem);
            subTotal = subTotal.add(total);

            if(orderService.isItemLack(item.getItemid(),cartItem.getQuantity())){
                items.add(item);
                isLack = true;
            }
            newOrderVO.setProductName(catalogService.getProduct(item.getProductid()).getName());
            newOrderVO.setCartItem(cartItem);
            newOrderVOList.add(newOrderVO);
        }
        if(isLack){
            session.setAttribute("items",items);
            return "redirect:/jsp/cart/cart";
        }


        model.addAttribute("VOList",newOrderVOList);
        model.addAttribute("subTotal",subTotal);
        return "/jsp/order/newOrder";
    }

    @RequestMapping("newOrderOk")
    public String newOrderOk(HttpServletRequest req){
        //对购物车内物品信息和订单信息进行处理
        HttpSession session = req.getSession();

        session.setAttribute("action","updateOrder");

        //先获取用户输入
        String firstName = req.getParameter("receiverFirstName");
        String lastName = req.getParameter("receiverLastName");
        String address1 = req.getParameter("shipToAddress1");
        String address2 = req.getParameter("shipToAddress2");

        //检查输入是否为空
        String msg = "";
        if(firstName==null||lastName==null||address1==null||address2==null){
            msg = "please finish the orders!";
            session.setAttribute("messageOrder",msg);
            return "redirect:/order/newOrder";
        }else if(firstName.isEmpty()||lastName.isEmpty()||address1.isEmpty()||address2.isEmpty()){
            msg = "please finish the orders!";
            session.setAttribute("messageOrder",msg);
            return "redirect:/order/newOrder";
        }
        session.setAttribute("messageOrder",msg);

        //再把购物车账号和订单都拿到手 注册的账号没存session！！记得改一下
        Order order = new Order();
        Account account = (Account) session.getAttribute("loginAccount");

        //分配订单编号
        try {
            order.setOrderId(orderService.getNextId("ordernum"));
        } catch (InvalidMidiDataException e) {
            throw new RuntimeException(e);
        }
        order.initOrder(account);

        //初始化order的总价和lineItems信息
        List<Cart> list = cartService.listByUserId(account.getUserid());
        ArrayList<CartItem> cartItems = new ArrayList<>();
        BigDecimal subTotal = BigDecimal.valueOf(0);
        List<LineItem>lineItems = new ArrayList<>();
        int lineNumber = 0;
        Boolean isLack = false;
        for (Cart cart : list) {
            CartItem cartItem = new CartItem();
            Item item = itemService.getById(cart.getItemId());
            cartItem.setItem(item);
            int quantity = cart.getQuantity();
            cartItem.setQuantity(quantity);
            cartItem.setItemId(item.getItemid());
            BigDecimal listprice = item.getListprice();
            BigDecimal total =  listprice.multiply(BigDecimal.valueOf(quantity));
            cartItem.setTotal(total);
            cartItems.add(cartItem);
            subTotal = subTotal.add(total);

            LineItem lineItem = new LineItem();
            lineItem.setOrderId(order.getOrderId());
            lineItem.setLineNumber(++lineNumber);
            lineItem.setItemId(item.getItemid());
            lineItem.setQuantity(cartItem.getQuantity());
            lineItem.setUnitPrice(item.getListprice());
            lineItems.add(lineItem);

            //减少库存量
            orderService.inventoryByItemId(cartItem.getItemId(),cartItem.getQuantity());
        }
        order.setTotalPrice(subTotal);

        //添加订单和lineItems到数据库
        try {
            orderService.insertOrder(order);
            orderService.insertLineItems(lineItems);
        } catch (InvalidMidiDataException e) {
            throw new RuntimeException(e);
        }

        //添加orderStatus
        orderService.insertOrderStatus(order);

        //最后清空购物车
        cartService.clearCart(account.getUserid());

        return "/jsp/order/orderSuccess";
    }
}
